package com.ccx.coachsite.ui.own;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import com.ccx.coachsite.R;
import com.ccx.coachsite.bus.ExpertInfo;
import com.ccx.coachsite.bus.ExpertMessage;
import com.ccx.coachsite.bus.ExpertProvider;
import com.ccx.coachsite.bus.SharedKey;
import com.ccx.coachsite.http.BitmapProgress;
import com.ccx.coachsite.http.ProgressListener;
import com.ccx.coachsite.ui.AppBaseView;
import com.ccx.coachsite.ui.login.LoginHelper;
import com.ccx.coachsite.ui.login.TopViewUtil;
import com.ccx.coachsite.util.SharedPreferencesUtil;
import com.ccx.coachsite.util.StringUtil;
import com.ccx.coachsite.webimage.ImageLoader;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Path.FillType;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AbsListView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class MyExpertView extends AppBaseView {

	public static final String TAG = "MyExpertView";

	private ExpertInfo expert;

	private TextView lblName, lblphone, lblRole, lblQQ;
	private ImageView imgStar;
	private ImageView imgHead;
	private GridView expertGrid;
	private ListView lstMessages;
	private Button btnCall, btnSend, btnRandom, btnAssign, btnOk;
	private EditText editorMessage;
	private ProgressDialog progressDialog;
	private View moreExpertLoading;
	private InputMethodManager imm;
	private View expertSelectorView, myExpertView, expertContentView,
			expertApplyView, expertConfirmView;
	private ExpertsAdpater expertListAdapter;
	private int expertPage = 1;

	private TextView messageText;
	private View sendbutton;

	private int seconds = 9;
	private AlertDialog dialog;

	Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			switch (msg.what) {
			case 1:
				seconds--;
				btnOk.setText("确定(" + String.valueOf(seconds) + ")");
				if (seconds <= 0)
					showContentView();
				break;
			case 2:
				btnOk.setText("确定");
				showContentView();
				break;
			}
		}
	};

	public MyExpertView(Context context) {
		super(context);
		// expertSelectorView = addChild(R.layout.expert_selector);
		myExpertView = addChild(R.layout.expert_my_expert);
		myExpertView.findViewById(R.id.login_btn_return).setVisibility(
				INVISIBLE);
		((TextView) myExpertView.findViewById(R.id.login_top_title))
				.setText("助理");
		TopViewUtil.updateTopTitle(this, R.id.login_top_title, "助理");
		expertContentView = myExpertView.findViewById(R.id.ll_expert_content);
		expertApplyView = myExpertView.findViewById(R.id.ll_expert_apply);
		expertConfirmView = myExpertView.findViewById(R.id.ll_expert_confirm);

		btnCall = (Button) myExpertView.findViewById(R.id.expert_btn_call);
		btnCall.setOnClickListener(btnCallClickListener);

		// expertGrid = (GridView)
		// expertSelectorView.findViewById(R.id.expert_selector_grid);
		// btnRandom = (Button)
		// expertSelectorView.findViewById(R.id.expert_btn_random);
		// btnAssign = (Button)
		// expertSelectorView.findViewById(R.id.expert_btn_assign);
		// expertGrid.setOnItemClickListener(expertClickListener);
		// btnRandom.setOnClickListener(btnRandomClickListener);
		// btnAssign.setOnClickListener(btnAssignClickListener);
		imm = (InputMethodManager) getContext().getSystemService(
				Context.INPUT_METHOD_SERVICE);

		editorMessage = (EditText) myExpertView
				.findViewById(R.id.expert_messnage_text);
		btnSend = (Button) myExpertView
				.findViewById(R.id.expert_messnage_send_button);
		btnSend.setOnClickListener(btnSendClickListener);
		// btnSend.setOnClickListener(new btnSendClickListener());
		refreshData();
	}

	class OnSendMessageListener implements OnClickListener {
		@Override
		public void onClick(View v) {

		}
	}

	@Override
	protected boolean onLoadData() {
		expert = ExpertProvider.getInstance().loadMyExpert(getContext());
		if (expert != null)
			return true;
		if (ExpertProvider.getInstance().getLastErrorCode() == ExpertProvider.NoClaimed)
			return true;
		return false;
	}

	@Override
	protected void onRefreshDataSuccess() {
		super.onRefreshDataSuccess();
		if (expert == null)
			showApplyView();
		else if (LoginHelper.isFirstLogin(getContext())) {
			showConfirmView();
			LoginHelper.setCurrentLogined(getContext());
		} else
			showContentView();
		switchView(myExpertView);
	}

	private void showApplyView() {
		expertContentView.setVisibility(GONE);
		expertApplyView.setVisibility(VISIBLE);
		expertConfirmView.setVisibility(GONE);

		Button btnApply = (Button) expertApplyView
				.findViewById(R.id.expert_apply_button);
		btnApply.setOnClickListener(btnApplyClickListener);
	}

	private void showContentView() {
		expertContentView.setVisibility(VISIBLE);
		expertApplyView.setVisibility(GONE);
		expertConfirmView.setVisibility(GONE);

		imgHead = (ImageView) expertContentView.findViewById(R.id.imgHead);
		lblName = (TextView) expertContentView.findViewById(R.id.lblName);
		lblphone = (TextView) expertContentView.findViewById(R.id.lblPhone);
		lblRole = (TextView) expertContentView.findViewById(R.id.lblRole);
		lblQQ = (TextView) expertContentView.findViewById(R.id.lblQQ);
		imgStar = (ImageView) expertContentView.findViewById(R.id.imgRank);

		ImageLoader.loadBitmap(expert.getIcon(), imgHead);
		lblName.setText(expert.getName());
		lblphone.setText(expert.getPhone());
		lblRole.setText(expert.getRole());
		if (TextUtils.isEmpty(expert.getQQ()))
			lblQQ.setText("未设置");
		else
			lblQQ.setText(expert.getQQ());
		switch (expert.getStar()) {
		case 1:
			imgStar.setImageResource(R.drawable.soft_mgr_star_1);
			break;
		case 2:
			imgStar.setImageResource(R.drawable.soft_mgr_star_2);
			break;
		case 3:
			imgStar.setImageResource(R.drawable.soft_mgr_star_3);
			break;
		case 4:
			imgStar.setImageResource(R.drawable.soft_mgr_star_4);
			break;
		case 5:
			imgStar.setImageResource(R.drawable.soft_mgr_star_5);
			break;
		default:
			imgStar.setImageResource(R.drawable.soft_mgr_star_0);
			break;
		}
		loadMessages();
	}

	private void showConfirmView() {
		expertContentView.setVisibility(GONE);
		expertApplyView.setVisibility(GONE);
		expertConfirmView.setVisibility(VISIBLE);

		ImageView imgHead = (ImageView) expertConfirmView
				.findViewById(R.id.imgHead);
		TextView lblName = (TextView) expertConfirmView
				.findViewById(R.id.lblName);
		TextView lblphone = (TextView) expertConfirmView
				.findViewById(R.id.lblPhone);
		ImageLoader.loadBitmap(expert.getIcon(), imgHead);
		lblName.setText(expert.getName());
		lblphone.setText(expert.getPhone());
		btnOk = (Button) expertConfirmView.findViewById(R.id.expert_confirm_ok);
		btnOk.setText("确定");
		btnOk.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				showContentView();
			}
		});
		// new CountDownTimer(10000, 1000) {
		//
		// @Override
		// public void onTick(long millisUntilFinished) {
		// handler.sendEmptyMessage(1);
		// }
		//
		// @Override
		// public void onFinish() {
		// handler.sendEmptyMessage(2);
		// }
		// }.start();
	}

	private void showWelcomeView() {
		dialog = new AlertDialog.Builder(getContext()).create();
		dialog.show();
		dialog.getWindow().setContentView(R.layout.expert_confirm_view);
		btnOk = (Button) dialog.findViewById(R.id.expert_confirm_ok);
		btnOk.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				dialog.dismiss();
			}
		});
		new CountDownTimer(10000, 1000) {

			@Override
			public void onTick(long millisUntilFinished) {
				handler.sendEmptyMessage(1);
			}

			@Override
			public void onFinish() {
				handler.sendEmptyMessage(2);
			}
		}.start();
	}

	public void loadMessages() {
		QueryMessagesTask task = new QueryMessagesTask();
		task.execute(0);
	}

	private void loadExpertList() {
		showLoading();
		if (this.expertList == null)
			this.expertList = new ArrayList<ExpertInfo>();
		moreExpertLoading = findViewById(R.id.expert_more_loading);
		expertListAdapter = new ExpertsAdpater();
		expertGrid.setAdapter(expertListAdapter);
		expertGrid.setOnScrollListener(expertListScrollListener);
		// expertSelectorView.findViewById(R.id.login_btn_return).setVisibility(View.INVISIBLE);
		// TextView txtTitle = (TextView)
		// expertSelectorView.findViewById(R.id.login_top_title);
		// txtTitle.setText(R.string.expert_topic);
		QueryExpertListTask task = new QueryExpertListTask();
		task.execute(1);
	}

	private void onLoadExpertListSuccess(List<ExpertInfo> experts) {
		this.expertList.addAll(experts);
		expertListAdapter.notifyDataSetChanged();
		moreExpertLoading.setVisibility(GONE);
		if (expertPage <= 1)
			switchView(expertSelectorView);
		expertPage++;
	}

	private void onLoadExpertListFail() {
		moreExpertLoading.setVisibility(GONE);
		onRefreshDataFail();
		Toast.makeText(getContext(), "对不起，无法加载助理列表", Toast.LENGTH_SHORT).show();
	}

	private void onLoadMessagesSuccess(List<ExpertMessage> result) {
		lstMessages = (ListView) myExpertView
				.findViewById(R.id.expert_message_list);
		lstMessages.setAdapter(new MessageAdapter(result));
		// lstMessages.setOnItemClickListener(listMessageClickListener);
	}

	private void onLoadMessagesFail() {
		Toast.makeText(getContext(), "加载消息列表失败", Toast.LENGTH_SHORT).show();
	}

	private void onSendMessageSuccess() {
		btnSend.setEnabled(true);
		setProgressVisible(false);
		editorMessage.setText("");
		loadMessages();
		switchView(myExpertView);
		Toast.makeText(getContext(), "消息已成功发送", Toast.LENGTH_SHORT).show();
	}

	private void onSendMessageFail() {
		btnSend.setEnabled(true);
		setProgressVisible(false);
		Toast.makeText(getContext(), "对不起，消息发送失败，请重试", Toast.LENGTH_SHORT)
				.show();
	}

	private void onExpertSelected(ExpertInfo expert) {
		this.expert = expert;
		setProgressVisible(false);
		// refreshData();
		showConfirmView();
		// showContentView();
		Toast.makeText(getContext(), "您的助理已分配", Toast.LENGTH_SHORT).show();
		// switchView(myExpertView);
	}

	private void onExpertSelectFail() {
		setProgressVisible(false);
		Toast.makeText(getContext(),
				ExpertProvider.getInstance().getLastErrorMessage(),
				Toast.LENGTH_SHORT).show();
	}

	private void onExpertSelectCanceled() {
		setProgressVisible(false);
	}

	private void setProgressVisible(boolean visible) {
		setProgressVisible(visible, null);
	}

	private void setProgressVisible(boolean visible, String message) {
		if (visible) {
			if (progressDialog == null)
				progressDialog = new ProgressDialog(getContext());
			progressDialog.setMessage(message);
			progressDialog.show();
		} else {
			if (progressDialog != null) {
				progressDialog.dismiss();
				progressDialog = null;
			}
		}
	}

	OnClickListener btnApplyClickListener = new OnClickListener() {

		@Override
		public void onClick(View v) {
			setProgressVisible(true, "正在申请，请稍候...");
			AutoAssignExpertTask task = new AutoAssignExpertTask();
			task.execute(0);
		}
	};

	OnItemClickListener expertClickListener = new OnItemClickListener() {

		private View lastSelected;

		@Override
		public void onItemClick(AdapterView<?> parent, View view, int position,
				long id) {
			ImageView imgRadio = null;
			if (lastSelected != null) {
				imgRadio = (ImageView) lastSelected
						.findViewById(R.id.expert_radio);
				imgRadio.setImageResource(R.drawable.ower_image_signal_unchecked);
			}
			if (view != null) {
				imgRadio = (ImageView) view.findViewById(R.id.expert_radio);
				imgRadio.setImageResource(R.drawable.ower_image_signal_checked);
				lastSelected = view;
				selectedPosition = position;
			}
		}
	};

	OnClickListener btnCallClickListener = new OnClickListener() {

		@Override
		public void onClick(View v) {
			Calendar calendar = Calendar.getInstance();
			calendar.setTimeInMillis(System.currentTimeMillis());
			if (calendar.get(Calendar.AM_PM) == Calendar.PM
					&& calendar.get(Calendar.HOUR) >= 10) {
				Toast.makeText(getContext(), "对不起，晚上10点后不允许呼叫助理",
						Toast.LENGTH_SHORT).show();
				return;
			}

			Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:"
					+ expert.getPhone()));
			intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
			getContext().startActivity(intent);
		}
	};

	OnClickListener btnSendClickListener = new OnClickListener() {

		@Override
		public void onClick(View v) {
			String message = editorMessage.getText().toString();
			if (TextUtils.isEmpty(message)) {
				Toast.makeText(getContext(), "请输入消息内容", Toast.LENGTH_SHORT)
						.show();
			} else if (message.length() > 280) {
				Toast.makeText(getContext(), "消息内容长度不得大于 280",
						Toast.LENGTH_SHORT).show();
			} else {
				imm.hideSoftInputFromWindow(editorMessage.getWindowToken(), 0);
				setProgressVisible(true, "正在发送...");
				v.setEnabled(false);
				SendMessageTask sendMessageTask = new SendMessageTask();
				sendMessageTask.execute(message);
			}
		}
	};

	OnClickListener btnMessageReturnClickListener = new OnClickListener() {

		@Override
		public void onClick(View v) {
			imm.hideSoftInputFromWindow(editorMessage.getWindowToken(), 0);
			switchView(myExpertView);
		}
	};

	OnClickListener btnRandomClickListener = new OnClickListener() {

		@Override
		public void onClick(View v) {
			setProgressVisible(true, "正在分配，请稍候...");
			RandomExpertTask task = new RandomExpertTask();
			task.execute(0);
		}
	};

	private List<ExpertInfo> expertList;
	private int selectedPosition = -1;
	OnClickListener btnAssignClickListener = new OnClickListener() {

		@Override
		public void onClick(View v) {

			if (selectedPosition < 0)
				Toast.makeText(getContext(), "请选择一个助理", Toast.LENGTH_SHORT)
						.show();
			else {
				setProgressVisible(true, "正在分配，请稍候");
				AssignExpertTask task = new AssignExpertTask();
				task.execute(expertList.get(selectedPosition));
			}
		}
	};

	OnScrollListener expertListScrollListener = new OnScrollListener() {

		@Override
		public void onScrollStateChanged(AbsListView view, int scrollState) {
			if (expertPage > ExpertProvider.getInstance().getExpertTotalPage())
				return;
			if (moreExpertLoading.getVisibility() == View.GONE
					&& view.getLastVisiblePosition() == expertListAdapter
							.getCount() - 1) {
				moreExpertLoading.setVisibility(VISIBLE);
				QueryExpertListTask task = new QueryExpertListTask();
				task.execute(expertPage);
			}
		}

		@Override
		public void onScroll(AbsListView view, int firstVisibleItem,
				int visibleItemCount, int totalItemCount) {

		}
	};

	class ExpertsAdpater extends BaseAdapter {

		@Override
		public int getCount() {
			return expertList.size();
		}

		@Override
		public Object getItem(int position) {
			return expertList.get(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			ExpertInfo expert = (ExpertInfo) getItem(position);
			View view = convertView != null ? convertView : View.inflate(
					getContext(), R.layout.expert_selector_item, null);
			ImageView imgPhoto = (ImageView) view
					.findViewById(R.id.expert_photo);
			TextView txtName = (TextView) view.findViewById(R.id.expert_name);
			imgPhoto.setImageResource(R.drawable.expert_default_head);
			ImageLoader.loadBitmap(expert.getIcon(), imgPhoto);
			txtName.setText(expert.getName());
			return view;
		}
	}

	class MessageAdapter extends BaseAdapter {

		private List<ExpertMessage> messages;
		private Bitmap myPhoto, herPhoto;
		private boolean loadingMyPhoto, loadingHerPhoto;

		public MessageAdapter(List<ExpertMessage> messages) {
			this.messages = messages;
		}

		@Override
		public int getCount() {
			return messages.size();
		}

		@Override
		public Object getItem(int position) {
			return messages.get(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			ExpertMessage message = (ExpertMessage) getItem(position);
			View view = convertView != null ? convertView : inflate(
					getContext(), R.layout.expert_message_item, null);
			ImageView myPhotoView = (ImageView) view
					.findViewById(R.id.expert_message_photo);
			ImageView herPhotoView = (ImageView) view
					.findViewById(R.id.expert_her_message_photo);
			TextView txtCreator = (TextView) view
					.findViewById(R.id.expert_message_creator);
			TextView txtTime = (TextView) view
					.findViewById(R.id.expert_message_time);
			TextView txtContent = (TextView) view
					.findViewById(R.id.expert_message_content);
			View layout = view.findViewById(R.id.expert_message_content_layout);
			if (message.isCreateBySelf()) {
				herPhotoView.setVisibility(GONE);
				myPhotoView.setVisibility(VISIBLE);
				layout.setBackgroundResource(R.drawable.expert_message_me);
				layout.setPadding(4, 0, 4, 2);
				// ImageLoader.loadBitmap(message.getIcon(), myPhotoView);
				if (myPhoto != null)
					myPhotoView.setImageBitmap(myPhoto);
				else
					loadMyPhoto(message.getIcon());
			} else {
				myPhotoView.setVisibility(GONE);
				herPhotoView.setVisibility(VISIBLE);
				layout.setBackgroundResource(R.drawable.expert_message_she);
				layout.setPadding(4, 0, 4, 2);
				// ImageLoader.loadBitmap(message.getIcon(), herPhotoView);
				if (herPhoto != null)
					herPhotoView.setImageBitmap(herPhoto);
				else
					loadHerPhoto(message.getIcon());
			}
			if (!IsShowTime(position))
				txtTime.setVisibility(GONE);
			else
				txtTime.setVisibility(VISIBLE);
			txtCreator.setText(message.getCreator());
			txtTime.setText(message.getTime());
			txtContent.setText(message.getContent());
			return view;
		}

		private void loadMyPhoto(String url) {
			if (StringUtil.isEmpty(url) || url.equals("null"))
				return;

			if (loadingMyPhoto)
				return;
			loadingMyPhoto = true;
			myPhoto = ImageLoader.loadBitmap(url,
					new ProgressListener<BitmapProgress>() {

						@Override
						public void onProgressUpdate(BitmapProgress entity) {

						}

						@Override
						public void onPostExecute(BitmapProgress entity) {
							myPhoto = entity.getBitmap();
							MessageAdapter.this.notifyDataSetInvalidated();
						}
					});
		}

		private void loadHerPhoto(String url) {
			if (StringUtil.isEmpty(url) || url.equals("null"))
				return;

			if (loadingHerPhoto)
				return;
			loadingHerPhoto = true;
			herPhoto = ImageLoader.loadBitmap(url,
					new ProgressListener<BitmapProgress>() {

						@Override
						public void onProgressUpdate(BitmapProgress entity) {

						}

						@Override
						public void onPostExecute(BitmapProgress entity) {
							herPhoto = entity.getBitmap();
							MessageAdapter.this.notifyDataSetInvalidated();
						}
					});
		}

		public boolean IsShowTime(int position) {
			if (position <= 0)
				return true;

			String strMt1 = ((ExpertMessage) getItem(position)).getTime();
			String strMt2 = ((ExpertMessage) getItem(position - 1)).getTime();

			if (StringUtil.isEmpty(strMt1) || strMt1.equals("null"))
				return false;

			if (StringUtil.isEmpty(strMt2) || strMt2.equals("null"))
				return true;

			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			// 得到指定模范的时间
			Date d1 = null;
			Date d2 = null;
			try {
				d1 = sdf.parse(strMt1);
				d2 = sdf.parse(strMt2);
			} catch (ParseException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			if (d1 == null || d2 == null)
				return true;

			long min = Math.abs(((d1.getTime() - d2.getTime()) / (60 * 1000)));

			if (min <= 5)
				return false;

			return true;
		}
	}

	class QueryExpertListTask extends
			AsyncTask<Integer, Integer, List<ExpertInfo>> {

		@Override
		protected List<ExpertInfo> doInBackground(Integer... params) {
			int page = params[0];
			return ExpertProvider.getInstance().loadExpertList(getContext(),
					page);
		}

		@Override
		protected void onPostExecute(List<ExpertInfo> result) {
			super.onPostExecute(result);
			if (result != null)
				onLoadExpertListSuccess(result);
			else
				onLoadExpertListFail();
		}

	}

	class QueryMessagesTask extends
			AsyncTask<Integer, Integer, List<ExpertMessage>> {

		@Override
		protected List<ExpertMessage> doInBackground(Integer... params) {
			return ExpertProvider.getInstance().loadExpertMessages(
					getContext(), expert);
		}

		@Override
		protected void onPostExecute(List<ExpertMessage> result) {
			super.onPostExecute(result);
			if (result != null)
				onLoadMessagesSuccess(result);
			else
				onLoadMessagesFail();
		}

	}

	class SendMessageTask extends AsyncTask<String, Integer, Boolean> {

		@Override
		protected Boolean doInBackground(String... params) {
			String message = params[0];
			return ExpertProvider.getInstance().sendMessage(getContext(),
					expert.getId(), message);
		}

		@Override
		protected void onPostExecute(Boolean result) {
			super.onPostExecute(result);
			if (result)
				onSendMessageSuccess();
			else
				onSendMessageFail();
		}
	}

	class RandomExpertTask extends AsyncTask<Integer, Integer, ExpertInfo> {

		@Override
		protected ExpertInfo doInBackground(Integer... params) {
			return ExpertProvider.getInstance().getRandomExpert(getContext());
			// return ExpertProvider.getInstance().assignExpert(getContext(),
			// expert);
		}

		@Override
		protected void onPostExecute(final ExpertInfo result) {
			super.onPostExecute(result);
			if (result != null) {
				new AlertDialog.Builder(getContext())
						.setTitle("随机选择")
						.setMessage(
								"系统为您随机分配了 " + result.getName()
										+ " 作为您助理，是否继续？")
						.setPositiveButton("是",
								new DialogInterface.OnClickListener() {

									@Override
									public void onClick(DialogInterface dialog,
											int which) {
										setProgressVisible(true, "正在分配，请稍候...");
										AssignExpertTask task = new AssignExpertTask();
										task.execute(result);
									}
								})
						.setNegativeButton("否",
								new DialogInterface.OnClickListener() {

									@Override
									public void onClick(DialogInterface dialog,
											int which) {
										onExpertSelectCanceled();
									}
								}).create().show();
			} else
				onExpertSelectFail();
		}
	}

	class AssignExpertTask extends AsyncTask<ExpertInfo, Integer, ExpertInfo> {

		@Override
		protected ExpertInfo doInBackground(ExpertInfo... params) {
			ExpertInfo expert = params[0];
			if (ExpertProvider.getInstance().assignExpert(getContext(), expert))
				return expert;
			return null;
		}

		@Override
		protected void onPostExecute(ExpertInfo result) {
			super.onPostExecute(result);
			if (result != null)
				onExpertSelected(result);
			else
				onExpertSelectFail();
		}
	}

	class AutoAssignExpertTask extends AsyncTask<Integer, Integer, ExpertInfo> {
		@Override
		protected ExpertInfo doInBackground(Integer... params) {
			ExpertInfo expert = ExpertProvider.getInstance().getRandomExpert(
					getContext());
			if (expert != null
					&& ExpertProvider.getInstance().assignExpert(getContext(),
							expert))
				return expert;
			return null;
		}

		@Override
		protected void onPostExecute(ExpertInfo result) {
			super.onPostExecute(result);
			if (result != null)
				onExpertSelected(result);
			else
				onExpertSelectFail();
		}
	}
}
